package com.xy6.dpdemo.book.chapter18.memento;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * 角色
 * 
 * @author zhang
 * @since 2017-06-25
 */
public class Roler implements Serializable {

	private static final long serialVersionUID = -4657030059486686076L;

	/** 生命力 */
	private Integer vitality;
	
	/** 攻击力 */
	private Integer attack;
	
	/** 防御力 */
	private Integer defence;
	
	public Integer getVitality() {
		return vitality;
	}

	public void setVitality(Integer vitality) {
		this.vitality = vitality;
	}

	public Integer getAttack() {
		return attack;
	}

	public void setAttack(Integer attack) {
		this.attack = attack;
	}

	public Integer getDefence() {
		return defence;
	}

	public void setDefence(Integer defence) {
		this.defence = defence;
	}

	@Override
	public String toString() {
		return "Roler [vitality=" + vitality + ", attack=" + attack + ", defence=" + defence + "]";
	}

	/**
	 * 备份
	 * <p>保存当前状态
	 * 
	 * @return
	 */
	public RolerState saveState(){
		RolerState state = new RolerState();
		state.setVitality(this.vitality);
		state.setAttack(this.attack);
		state.setDefence(this.defence);
		
		return state;
	}
	
	/**
	 * 恢复
	 * <p>从某一状态中恢复
	 * 
	 * @param state
	 */
	public void recoverState(RolerState state){
		this.setVitality(state.getVitality());
		this.setAttack(state.getAttack());
		this.setDefence(state.getDefence());
	}

	/**
	 * 深度复制
	 */
	public Roler deepClone(){
		try {
			ByteArrayOutputStream bo = new ByteArrayOutputStream();
			ObjectOutputStream oo = new ObjectOutputStream(bo);
			oo.writeObject(this);
			
			ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
			ObjectInputStream oi = new ObjectInputStream(bi);
			
			return (Roler) oi.readObject();
		} catch (IOException e) {
			e.printStackTrace();
			throw new InternalError();
		} catch(ClassNotFoundException e){
			e.printStackTrace();
			throw new InternalError();
		}
	}
	
	/**
	 * 初始状态
	 */
	public void initState(){
		this.setVitality(1000);
		this.setAttack(2000);
		this.setDefence(800);
	}
	
	/**
	 * 打boss
	 */
	public void fightBoss(){
		this.setVitality(0);
		this.setAttack(0);
		this.setDefence(0);
	}
	
}
